package com.ddy.test.util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

/**
 * 处理AES加密解密
 * 
 * @author yangwh
 * 
 */
public class AESUtils {

	public static byte[] encryptAES(String content, String password) {
		try {
			SecretKeySpec secretKeySpec = new SecretKeySpec(
					generateKey(password.getBytes()), "AES");
			Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding","BC");// 创建密码器
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化
			byte[] result = cipher.doFinal(content.getBytes());
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		}
		throw new RuntimeException("加密错误，请检查配置文件的appkey等配置参数。");
	}

	public static byte[] generateKey(byte[] seed) throws NoSuchAlgorithmException, NoSuchProviderException {
		if (seed.length > 16) {
			int p=seed.length/16;
			byte[] key = new byte[16];
			for (int i = 0; i < 16; i++){
				int index=(i*p)+(i%p);
//				System.out.println(index);
				key[i] = seed[index];
			}
			return key;
		} else {
			int i = 0;
			byte[] key = new byte[16];
			for (; i < seed.length; i++)
				key[i] = seed[i];
			for (; i < 16; i++)
				key[i] = 59;
			return key;
		}
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param password
	 *            解密密钥
	 * @return
	 * @throws Exception 
	 */
	public static byte[] decrypt(byte[] content, String password) {
		try {
			SecretKeySpec secretKeySpec = new SecretKeySpec(
					generateKey(password.getBytes()), "AES");
			Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding","BC");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		}
		throw new RuntimeException("解密错误，请检查配置文件的appkey等配置参数。");
	}
}

